// axios基础的封装
import axios from 'axios'

import {ElMessage} from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'

import {useUserStore} from '@/stores/user'

import router from "@/router"


const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    // baseURL: 'http://47.96.75.125/test',

    timeout: 5000,
})

// 拦截器
// axios请求拦截器
httpInstance.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        const userInfo = userStore.userInfo

        // 1.从pinia中获取token
        const token = userInfo.token
        // 2.按照后端的要求拼接token数据
        if (token) {
            // 记住，Bearer后面会有一个空格
            config.headers.Authorization = `Bearer ${token}`
        }
        // let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTcxMTE3MzAzMiwianRpIjoiNWFhOTA4NDQtM2MzMS00YWRkLWJlOTQtYTJlOTAwYTRhYmE4IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6InJvb3QiLCJuYmYiOjE3MTExNzMwMzIsImNzcmYiOiJkOTM2YmRiNS02ODRjLTQ1OGQtOTU4MS0zY2ZlYmE1YWZjN2MiLCJleHAiOjE3MTEyNTk0MzJ9.ea00o91u6eZPisdhlmyOwSGhajRSDKyIY4RNmR3vUQ0"
        config.headers.Authorization = `Bearer ${token}`
        return config
    },
    (e) => Promise.reject(e)
)

// axios响应拦截器
httpInstance.interceptors.response.use(
    (res) => res.data,
    (e) => {
        console.log(router)
        const userStore = useUserStore()

        // 错误提示统一
        // console.log(e)
        ElMessage({type: 'error', message: e.response.data.msg})
        // 401token失效处理
        //1. 清除本地用户数据
        //2. 跳转到登录页
        if (e.response.status === 401) {
            userStore.clearUserInfo()
            router.push('/login')
        }
        return Promise.reject(e)
    }
)

export default httpInstance
